其他
改进Spring Boot REST API错误处理
(给ImportNew加星标,提高Java技能)
来自作者投稿 作者:覃佑桦
dzone.com/articles/rest-api-error-handling-with-spring-boot
· 默认错误有时候看起来比较混乱:
{
"timestamp": "2018-09-23T15:05:32.681+0000",
"status": 400,
"error": "Bad Request",
"errors": [
{
"codes": [
"NotBlank.dto.name",
"NotBlank.name",
"NotBlank.java.lang.String",
"NotBlank"
],
"arguments": [
{
"codes": [
"dto.name",
"name"
],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}
],
"defaultMessage": "{name.not_blank}",
"objectName": "dto",
"field": "name",
"rejectedValue": null,
"bindingFailure": false,
"code": "NotBlank"
}
],
"message": "Validation failed for object='dto'. Error count: 1",
"path": "/"
}
public class UserAlreadyExistsException extends RuntimeException {
// How can I expose this value to the interpolated message?
private final String username;
// constructors and getters and setters
}
改进方案
默认错误显示
// errors数组为每个错误都定义了code/messsge组合
{
"errors": [
{
"code": "first_error_code",
"message": "1st error message"
}
]
}
统一错误处理
内建错误码支持
@ExceptionMapping(statusCode = BAD_REQUEST, errorCode = "user.already_exists")
public class UserAlreadyExistsException extends RuntimeException {}
public class ExistedUserHandler implements WebErrorHandler {
@Override
public boolean canHandle(Throwable exception) {
return exception instanceof UserAlreadyExistsException;
}
@Override
public HandledException handle(Throwable exception) {
return new HandledException("user.already_exists", BAD_REQUEST, null);
}
}
暴露参数
与Spring Boot一样,你也可以通过注解传递验证参数,例如用@Min(value = 18, message = "age.min")把参数内插到显示的消息中:
age.min = The minimum age is {0}!
此外,还可以使用@ExposeAsArg注解自定义异常。例如,如果在下面的消息中报告username已被占用:
user.already_exists=Another user with the '{0}' username already exists
实现代码:
@ExceptionMapping(statusCode = BAD_REQUEST, errorCode = "user.already_exists")
public class UserAlreadyExistsException extends RuntimeException {
@ExposeAsArg(0) private final String username;
// constructor
}
总结
看完本文有收获?请转发分享给更多人
关注「ImportNew」,提升Java技能
好文章,我在看❤️